package com.jming.jike.util;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jming.jike.entity.Orders;
import com.jming.jike.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * redis过期监听
 *
 * @author jinming.zhang
 * @version 0.0.1
 * @date 2022/05/20
 */
@Slf4j
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    @Resource
    private OrdersMapper ordersMapper;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 修改订单信息
     *
     * @param message
     * @param pattern
     * @return void
     * @Author jinming.zhang
     * @Date 2022/5/20
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {

        // 过期的key
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("redis key 过期：{}", key);

        // 验证码过期 不做任何处理
        if (key.contains("getCode_")) {
            return;
        }
        // 修改订单状态
        Long userId = Long.valueOf(key.replace("createOrders_", ""));

        // 取消用户待付款的订单
        int update = ordersMapper.update(null, Wrappers.<Orders>lambdaUpdate()
                .eq(Orders::getUserId, userId)
                .eq(Orders::getStatus, 1)
                .set(Orders::getStatus, 5));
        log.info("超时自动取消订单, 用户 {} 操作状态 {}", userId, update);
    }
}
